import Loayout from '@/layout/index.vue'
import { VuexModule, getModule, Module, Mutation, Action } from 'vuex-module-decorators'
import { RouteRecordRaw } from 'vue-router'
import asyncRoutes from '@/router/routes'
import store from '@/store'

export interface IPermissionState {
  isInited: boolean
  routes: RouteRecordRaw[] // 服务器匹配到的routes，主要用于生成导航栏
  otherRoutes: RouteRecordRaw[] // 本地其他用于测试的routes
}
export interface RoterConfigRaw {
  id: number
  parentId: number
  path: string
  icon?: string
  title?: string
}
// 后台去配置这个roter
const routerCcofnig: RoterConfigRaw[] = [
  { id: 1, parentId: 0, title: '待办看板', path: '/', icon: 'dashboard' },
  { id: 100, parentId: 0, title: '组件库', path: '', icon: 'component' },
  { id: 101, parentId: 100, path: '/demo_svg_icon' },
  { id: 102, parentId: 100, path: '/common_demo' },
  { id: 103, parentId: 100, path: '/demo_echarts' },
  { id: 104, parentId: 100, path: '/demo_sortabale' },
  { id: 200, parentId: 0, title: 'css3 基础', path: '', icon: 'CSS3' },
  { id: 201, parentId: 200, path: '/css3_transition' },
  { id: 202, parentId: 200, path: '/css3_animation' },
  { id: 203, parentId: 200, path: '/css3_transform' }
]
/**
 * parentId = 0 && path 有值 = 1级菜单可点击
 */
const filterData = () => {
  const routes: any = []
  const routerMap = {}
  const otherRoutes: any = []
  // 从数据库获取 routerconfig
  const len = routerCcofnig.length
  for (let i = 0; i < len; i++) {
    const obj = routerCcofnig[i]
    // 构建1级主菜单
    if (obj.parentId === 0) {
      routerMap[`_root_${obj.id}`] = {
        path: `/root_${obj.id}`,
        component: Loayout,
        name: `root_${obj.id}`,
        redirect: obj.path || '',
        meta: {
          icon: obj.icon,
          title: obj.title
        },
        children: []
      }
    }
  }
  // 构建子菜单
  for (let i = 0; i < len; i++) {
    const obj = routerCcofnig[i]
    if (!obj.path && obj.parentId === 0) continue
    for (const key of Object.keys(asyncRoutes)) {
      const { children, ...o } = asyncRoutes[key]
      if (o.path === obj.path) {
        // 子组件
        const sub = {
          ...o,
          meta: {
            ...o.meta,
            icon: obj.icon || o.meta?.icon,
            title: obj.title || o.meta?.title,
            breadcrumb: !!obj.parentId
          }
        }
        // 如果是单节点
        const routerObj = routerMap[`_root_${obj.parentId || obj.id}`]
        if (!routerObj.redirect) {
          routerObj.redirect = o.path
        }
        routerObj.children.push(sub)
        // 添加子子级
        if (children?.length) {
          children.forEach(t => {
            const { meta, ...i } = t
            routerObj.children.push({
              ...i,
              meta: {
                ...meta,
                // 注意：这里的 hidden 跟 router 里直接写的意义不一样
                __hidden__: true
              }
            })
          })
        }
        // 已经初始化
        (o as any).inited = true
      }
    }
  }
  // 注册路由 带菜单
  for (const key in routerMap) {
    routes.push(routerMap[key])
  }
  // 注册路由不带菜单
  for (const key in asyncRoutes) {
    const o = asyncRoutes[key]
    if (!(o as any).inited) {
      if (!o.meta?.hidden) {
        otherRoutes.push({
          path: o.path,
          component: Loayout,
          redirect: o.path,
          children: [o]
        })
      } else {
        // 不显示在容器里
        otherRoutes.push(o)
      }
    }
  }
  return { routes, otherRoutes }
}

@Module({ namespaced: true, store, name: 'permission', dynamic: true })
class Permission extends VuexModule implements IPermissionState {
  public isInited = false
  public routes: RouteRecordRaw[] = []
  public otherRoutes = []
  @Mutation
  SET_ROUTER(routers) {
    this.routes = routers
  }

  @Mutation
  SET_ININTED(status: boolean) {
    this.isInited = status
  }

  @Mutation
  SET_OTHER_ROUTES(routes) {
    this.otherRoutes = routes
  }

  @Action
  // 设置app初始化标识
  setInitStatus(status: boolean) {
    this.SET_ININTED(status)
  }

  @Action
  // 生成路由 generateRoutes
  async generateRoutes() {
    // 后台请求菜单列表
    // const resData = await getMenuList({ appKey: 'pandora_run' })
    // console.log(resData)
    const { routes, otherRoutes } = filterData()
    // 模拟从数据库中获取
    // const prosi = new Promise((resolve) => {
    //   setTimeout(() => {
    //     resolve({})
    //   }, 1000)
    // })
    // // 注册路由 (提取出去，setRouter )
    // const a = await prosi
    this.SET_ROUTER(routes)
    this.SET_OTHER_ROUTES(otherRoutes)
  }
}
export const permissionStore = getModule<Permission>(Permission)
